package unq.tpi.persistencia.alumnos.arq.runner;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import unq.tpi.persistencia.alumnos.arq.Service;

public class HibernateRunner implements Runner{

	private static SessionFactory sessionFactory = init();
	private static ThreadLocal<Session> sessionHolder = new ThreadLocal<Session>();
	
	public <T> T run(Service<T> service) {
		Session session = null;
		T result;

		try{
			session = sessionFactory.openSession();
			session.beginTransaction();
			sessionHolder.set(session);
			
			result = service.execute();
			
			session.flush();
			session.getTransaction().commit();
			
			return result;
		}catch(RuntimeException e){
			if(session != null)
				if(session.getTransaction().isActive())
					session.getTransaction().rollback();
			throw e;
		}finally{
			if(session != null)
				session.close();
		}
	}

	private static SessionFactory init() {
		Configuration cfg = new Configuration();
		cfg.configure();
		
		return cfg.buildSessionFactory();
	}

	public static Session currentSession(){
		return sessionHolder.get();
	}
}
